package com.app.controller.miniProgram;

import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.MyScoreVo;
import com.app.vo.ScoreVo;
import com.app.vo.ScoresVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@RestController
@Controller
@RequestMapping("/api/scores")
public class ScoresController {
   @Autowired
   UserService userService;
    @Autowired
    FormService formService;
    @Autowired
    AttService attService;
    @Autowired
    ScoresService scoresService;
    @Autowired
    FormUrlService formUrlService;

    @GetMapping("/getScoreList")//积分榜
    public Result<Object> getScoreList(
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String uid = TokenUtils.verify(token);
        if (uid.equals("false")){
            return Result.error(405,"token已过期");
        }
        UserModel userModel = userService.getUserById(Integer.parseInt(uid));
        if (userModel == null) {
            return Result.error(406, "用户不存在");
        }
        List<ScoresVo> sortList = scoresService.selectScoresSort();//查询出排行榜
        List<ScoresVo> sortVo = new ArrayList<>();
        for (int i = 0; i < sortList.size(); i++) {
            if(i<50)
            {
                sortVo.add(sortList.get(i));
            }else {
                break;
            }

        }
        for (int i = 0; i < sortVo.size(); i++) {//循环查出是否有自己

            if(userModel.getId().equals(sortVo.get(i).getUserId()))
            {
                sortVo.get(i).setIsMe(1);
            }
        }
        ScoresVo vo = new ScoresVo();
        int sort = 0;
        int score = 0;
        for (int i = 0; i < sortList.size(); i++) {//循环查出自己排名
            if(sortList.get(i).getUserId().equals(userModel.getId()))
            {
                sort = i+1;
                score = sortList.get(i).getScore();
                break;
            }
        }
        vo.setSort(sort);
        vo.setScore(score);
        vo.setUserName(userModel.getUserName());
        ScoreVo scoreVo = new ScoreVo();
        scoreVo.setMyScore(vo);
        scoreVo.setSortList(sortVo);
        return Result.success(scoreVo);
    }
    @PostMapping("/insertScores")//    新增积分(加或者减)
    public Result<Object> insertScores(
            @RequestParam("id") Integer id,
            @RequestParam("userId") Integer userId,
            @RequestParam("score") Integer score,
            @RequestParam("operateType") Integer operateType,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String uid = TokenUtils.verify(token);
        if (uid.equals("false")){
            return Result.error(405,"token已过期");
        }
        UserModel userModel = userService.getUserById(Integer.parseInt(uid));
        if (userModel == null) {
            return Result.error(406, "用户不存在");
        }
        List<ScoresModel> modelList = scoresService.getScoresListByUserId(userModel.getId());
        if(modelList.size() != 0){
                     if(operateType == 1 || operateType == 2){
                         ScoresModel scoresModel = new ScoresModel();
                         scoresModel.setUserId(userId);
                         scoresModel.setScore(score);
                         scoresModel.setOperateType(operateType);
                         scoresModel.setAfterScore(modelList.get(0).getAfterScore() + score);
                         scoresModel.setCrtTime(CommonHelp.getNowTimestamp());
                         scoresService.insert(scoresModel);
                     }else if(operateType == 3){
                         ScoresModel scoresModel = new ScoresModel();
                         scoresModel.setUserId(userId);
                         scoresModel.setScore(score);
                         scoresModel.setOperateType(operateType);
                         scoresModel.setAfterScore(modelList.get(0).getAfterScore() - score);
                         scoresModel.setCrtTime(CommonHelp.getNowTimestamp());
                         scoresService.insert(scoresModel);
                     }else if(operateType == 4){
                         ScoresModel scoresModel = new ScoresModel();
                         scoresModel.setUserId(userId);
                         scoresModel.setScore(score);
                         scoresModel.setOperateType(operateType);
                         scoresModel.setAfterScore(0);
                         scoresModel.setCrtTime(CommonHelp.getNowTimestamp());
                         scoresService.insert(scoresModel);
                     }
        }else {
            ScoresModel scoresModel = new ScoresModel();
            scoresModel.setUserId(userId);
            scoresModel.setScore(score);
            scoresModel.setAfterScore(score);
            scoresModel.setOperateType(operateType);
            scoresModel.setCrtTime(CommonHelp.getNowTimestamp());
            scoresService.insert(scoresModel);
        }
        return Result.success(null);
    }
    @GetMapping("/getFormById")//详情
    public Result<Object> updateStatus(
            @RequestParam("page") Integer page,
            @RequestParam("limit") Integer limit,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String uid = TokenUtils.verify(token);
        if (uid.equals("false")){
            return Result.error(405,"token已过期");
        }
        UserModel userModel = userService.getUserById(Integer.parseInt(uid));
        if (userModel == null) {
            return Result.error(406, "用户不存在");
        }
        Page<ScoresModel> scoresModelPage = scoresService.getPageScoresById(page,limit,userModel.getId());
        if(scoresModelPage.getRecords().size()==0){
            return Result.success(null);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (int i = 0; i < scoresModelPage.getRecords().size(); i++) {
            if (scoresModelPage.getRecords().get(i).getCrtTime() != null) {
                String crtTime = sdf.format(scoresModelPage.getRecords().get(i).getCrtTime());
                scoresModelPage.getRecords().get(i).setCrtTimeText(crtTime);
            }
        }
        int count = (int) scoresModelPage.getTotal();
        List<ScoresModel> scoresModelList;
        scoresModelList = scoresModelPage.getRecords();
        MyScoreVo vo = new MyScoreVo();
        ScoresModel myScores = scoresModelList.get(0);//取出自己的数据
        vo.setCount(count);
        vo.setMyScore(myScores.getAfterScore());
        vo.setSortList(scoresModelList);
        return Result.success(vo);


    }
    @GetMapping("/deleteById")//删除
    public Result<Object> deleteById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String uid = TokenUtils.verify(token);
        if (uid.equals("false")){
            return Result.error(405,"token已过期");
        }
        UserModel userModel = userService.getUserById(Integer.parseInt(uid));
        if (userModel == null) {
            return Result.error(406, "用户不存在");
        }
        FormModel formModel = formService.getFormById(id);
        if(formModel == null){
            return Result.error(500,"该条数据不存在");
        }else {
            formService.delete(id);
            return Result.success(null);
        }
    }
}
